import { uploadChunk, uploadMerge } from "@/api/file"
import { ElMessage } from "element-plus";


export const uploadFile = async (file) => {
	// 使用正则表达式匹配中文字符
	const regex = /[\u4e00-\u9fa5]/;
	const flag = regex.test(file.name);
	if (flag) return ElMessage.error("上传文件不能包含中文")
	const chunkSize = 5 * 1024 * 1024; // 5MB
	const totalChunks = Math.ceil(file.size / chunkSize);

	for (let i = 0; i < totalChunks; i++) {
		const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
		const formData = new FormData();
		formData.append('file', chunk);
		formData.append('chunkIndex', i);
		formData.append('chunkTotal', totalChunks);
		formData.append('identifier', file.name);

		await uploadChunk(formData)
	}

	const mergeFormData = new FormData();
	mergeFormData.append('chunkTotal', totalChunks);
	mergeFormData.append('identifier', file.name);
	// 合并切片
	const res = await uploadMerge(mergeFormData)
	ElMessage.success("上传成功")
	return res
}
